﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Mysqlx;
using Mysqlx.Crud;
using MySqlX.XDevAPI.Common;
using Newtonsoft.Json;
using ServiceStack;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZH.Infrastructure.Attr;
using ZH.Infrastructure.Dto.Request.Login;
using ZH.Infrastructure.Dto.Request.Mobile;
using ZH.Infrastructure.Dto.Response;
using ZH.Infrastructure.Dto.Response.admin;
using ZH.Infrastructure.Dto.Response.Promotion;
using ZH.Infrastructure.EFCore.MySql;
using ZH.Infrastructure.IOC;
using ZH.Infrastructure.Redis;
using ZH.Infrastructure.Tools;
using ZH.Service.Interface;

namespace ZH.Service.Instance
{
    [Inject_]
    public class Mobile_Service : Base_Service, I_Mobile_Service
    {
        private readonly RedisStringService _redisStringService;
        public readonly IConfiguration _configuration;
        public  readonly Mobile_IOC _mobile_IOC;

        public Mobile_Service(
            Mobile_IOC mobile_IOC,
            IConfiguration configuration,
            RedisStringService redisStringService
            

            ) {
            _redisStringService = redisStringService;
            _configuration = configuration;
            _mobile_IOC = mobile_IOC;
        }


        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        /// <param name="code"></param>
        /// <param name="account"></param>
        /// <returns></returns>
        public User_Response_Dto? Check_Login(string? code, string account)
        {
            var _user = _redisStringService.Get<string>(code!);//获取用户信息

            if (!string.IsNullOrEmpty(_user))//获取到了代表当前code是有效的
            {
                return JsonConvert.DeserializeObject<User_Response_Dto>(_user);
                //直接把信息返回回去即可
            }

            //没有获取到用户信息


            var key = _configuration["Redis:Keys:Mobile_Check_Login"];
            //如果在此处你查询了这个
            var jwt = _redisStringService.Get<string>(key + account);//是否是有效的code 最后一个code
            if (code == jwt)
            {
                //300ms 变成了3s
                var user = _mobile_IOC._mobile_EFCore.QueryAll(d => d.Maccount == account).Select(d => new
                User_Response_Dto
                {
                    id = d.Mid,
                    name = d.Mname,
                    account = d.Maccount,
                    isActive = d.MisActive,
                    isBan = d.MisBan,
                    time = d.McreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss")
                }).Single();
                _redisStringService.Set(code, JsonConvert.SerializeObject(user), DateTime.Now.AddSeconds(60));
                return user;
            }
            else
                return null;
        }

        public async Task<Api_Response_Dto> Logins(Login_Request_Dto dto)
        {
            var iq = _mobile_IOC._mobile_EFCore.QueryAll(d => d.Maccount == dto.account||d.Email==dto.account);
         
            if (!await iq.AnyAsync())
            {
                return Result(0, "账号或者密码错误！");
            }

            var supplier = await iq.SingleAsync();
            var pwd = EncryptUtil.LoginMd5(dto.password!, supplier.Msalt!);
            if (supplier.Mpassword != pwd)
            {
                return Result(0, "账号或者密码错误！");
            }

            if (supplier.MisBan == 1)
            {
                return Result(0, "账号已禁用");
            }
            dto.account = iq.FirstOrDefault().Maccount;
            //添加登录日志
            Mobileloginlog supplierLoginLog = new Mobileloginlog()
            {
                MlAccount = supplier.Maccount,
                MlName = supplier.Mname,
                MlCode = dto.code,
                MlCreateTime = DateTime.Now,
                MlId = Config.GUID(),
                MlIp = Config.GetIp(),
            };
            _mobile_IOC._mobileloginlog_EFCore.Add(supplierLoginLog);

            if (supplier.MisActive == 0)
            {
                supplier.MisActive = 1;
                _mobile_IOC._mobile_EFCore.Update(supplier);
            }
            _mobile_IOC._mobileloginlog_EFCore.SaveChanges();
            _mobile_IOC._mobile_EFCore.SaveChanges();
            //事务
            //var result = _supplier_IOC._supplier_Login_log.Transactions(_supplier_IOC._supplier_EFCore);

            //redis 保存code
            if (true)
            {
                //事务成功就是登录完成了 存入redis
                var key = _configuration["Redis:Keys:Mobile_Check_Login"];
                _redisStringService.Set<string>(key + supplier.Maccount, dto.code!, DateTime.Now.AddSeconds(60 * 60 * 24));//一天有效

            }

            return Result(true ? 1 : 0);
        }

        public async Task<Api_Response_Dto> get_Nmoble(int? page, int? limt, string? key)
        {
            var data = await _mobile_IOC._mobile_EFCore.QueryAll(out int total,
                Convert.ToInt32(page), Convert.ToInt32(limt),
                true,
                o => o.Mid,d=>string.IsNullOrEmpty(key) || d.Mname.Contains(key)
                ).ToListAsync();
            return Result(1, "ok", new
            {
                total,
                data
            });


        }

        public async Task<Api_Response_Dto> Get_Rmoble(int? page, int? limit, string? key)
        {
            // 获取当天的起始和结束时间
            DateTime todayStart = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
            DateTime todayEnd = todayStart.AddDays(1).AddTicks(-1);

            // 查询当天的订单并分页
            var data = await _mobile_IOC._mobile_EFCore.QueryAll(
                out int total,
                Convert.ToInt32(page),
                Convert.ToInt32(limit),
                true,
                o => o.Mid,  // 排序字段
                d => d.McreateTime >= todayStart && d.McreateTime <= todayEnd  // 筛选条件：当天的订单
            ).ToListAsync();

            return Result(1, "ok", new
            {
                total,
                data
            });
        }

        public Api_Response_Dto Register(string email, string password,string phone)
        {
            Random random = new Random();

            var s = Config.GUID2();
            Mobile m = new Mobile();
            m.Mid = Config.GUID();
            m.Mname = "用户:"+ phone;
            m.Maccount = phone;
            m.Mphone = phone;
            m.Email = email;
            m.Msalt = s;
            m.Mpassword = EncryptUtil.LoginMd5(password, s);
            m.MisBan = 0;
            m.MisActive = 1;
            m.McreateTime = DateTime.Now;
            m.MemberLevel = "普通会员";
            _mobile_IOC._mobile_EFCore.Add(m);
            _mobile_IOC._mobile_EFCore.SaveChanges();
            return Result(1, "注册成功，请返回登录页面登录");

        }

        public async Task<Api_Response_Dto> Add_copywriting(Copywriting_Response_Dto dto)
        {
           Copywriting ls=new Copywriting();      
            ls.CId = Config.GUID();
            ls.CTime = DateTime.Now;
            ls.Cbody=dto.cbody;
            ls.CLength=dto.cLength;
            ls.Ctype=dto.ctype;

            _mobile_IOC._copywriting_EFCore.Add(ls);
            var result=await _mobile_IOC._copywriting_EFCore.SaveChangesAsync();
            return Result(result, "添加成功");

           
        }

        public async Task<Api_Response_Dto> delete_copywriting(string id)
        {
            var ls = await _mobile_IOC._copywriting_EFCore.QueryAll(d => d.CId == id).FirstOrDefaultAsync();
            _mobile_IOC._copywriting_EFCore.Delete(ls);
            var result = _mobile_IOC._copywriting_EFCore.SaveChanges();

            return Result(result, "删除成功");

        }

        public async Task<Api_Response_Dto> update_copywriting(Copywriting_Response_Dto dto)
        {
          var data=await _mobile_IOC._copywriting_EFCore.QueryAll(d=>d.CId==dto.cId).FirstOrDefaultAsync();




            data.Cbody = dto.cbody;
            data.CLength = dto.cLength;
            data.Ctype = dto.ctype;
            _mobile_IOC._copywriting_EFCore.Update(data);



            var result =  _mobile_IOC._copywriting_EFCore.SaveChanges();
            return Result(result, "修改成功");
        }

        public async Task<Api_Response_Dto> Get_Cashier_Single_Mobile(string phone)
        {
            var mobile = await _mobile_IOC._mobile_EFCore.QueryAll(m => m.Mphone == phone && m.MisBan == 0 && m.MisActive == 1).FirstOrDefaultAsync();

            if (mobile != null)
            {
                return Result(1, "查询成功", mobile );
            }
            else {
                return Result(0,"查询失败");
            }
        }

        public async Task<Api_Response_Dto> Cashier_Add_Mobile(Mobile_Cashier_Request_Dto dto)
        {
            Mobile mobile = new Mobile()
            {
                Mid = Config.GUID(),
                Maccount = "",
                Mpassword = "",
                Email = "",
                Mname = dto.name,
                Mgender = dto.gender,
                Mphone = dto.phone,
                Mbirthday = null,
                MemberLevel = "新用户",
                MemberStatus = null,
                Mregister = null,
                ReferrerId = null,
                McreateTime = DateTime.Now,
                MisBan = 0,
                MisActive = 1,
                Msalt = "",
                Mdesc = "收银端新增的客户"
            };

            _mobile_IOC._mobile_EFCore.Add(mobile);

            var count = await _mobile_IOC._mobile_EFCore.SaveChangesAsync();

            if (count > 0)
            {
               return Result(1, "ok");
            }
            else {
               return Result(0);
            }
        }
    }
}
